<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>昌西的西昌</title>
    <!-- 引入 Element UI 样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui@2.15.13/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f7f6;
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            position: relative;
        }

        /* 水印样式 */
        #watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 100px;
            color: rgba(200, 200, 200, 0.2);
            pointer-events: none;  /* 让水印不可点击 */
            z-index: -1;
        }

        /* 加载动画样式 */
        #loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none; /* 初始隐藏 */
        }

        .spinner-overlay {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #48c78e;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 消息区域样式 */
        #chat-container {
            width: 600px; /* 固定宽度 */
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            box-sizing: border-box;
            position: relative;
            z-index: 1;
            display: flex;
            flex-direction: column;
            height: 80vh; /* 固定高度 */
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        #messages {
            height: 420px;
            border-radius: 8px;
            border: 1px solid #ddd;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
            box-shadow: inset 0px 4px 6px rgba(0, 0, 0, 0.05);
        }

        .message {
            margin: 10px 0;
            padding: 10px 15px;
            border-radius: 8px;
            box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
            max-width: 80%;
            word-wrap: break-word;
            /* 移除 clear: both; 和 position: relative; */
        }

        .message.user {
            background-color: #d1fddc; /* 浅绿色 */
            text-align: right;
            margin-left: 100px;
            align-self: flex-end;      /* 新增 */
        }

        .message.assistant {
            background-color: #ffffff; /* 浅蓝色 */
            text-align: left;
            align-self: flex-start;    /* 新增 */
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #48c78e;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-left: 10px;
        }

        /* 图片预览样式 */
        #image-preview {
            margin-top: 10px;
            max-width: 100%;
            max-height: 150px;
            display: none; /* 初始隐藏 */
            border-radius: 8px;
            box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
        }

        /* Scrollbar customization */
        #messages::-webkit-scrollbar {
            width: 8px;
        }

        #messages::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb {
            background: #bbb;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb:hover {
            background: #888;
        }
        *, *::before, *::after {
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <!-- 添加水印 -->
    <div id="watermark">昌西</div>

    <!-- 加载动画 -->
    <div id="loading-overlay">
        <div class="spinner-overlay"></div>
    </div>

    <div id="chat-container">
        <!-- Vue 应用将接管这里 -->
        <div id="app">
            <!-- 标题和新增对话按钮 -->
            <div class="header">
                <h2>西昌</h2>
                <el-button type="primary" icon="el-icon-plus" @click="createNewConversation" :disabled="loading"></el-button>
            </div>

            <!-- 消息显示区域 -->
            <div id="messages">
                <div v-for="msg in messages" :key="msg.id" :class="['message', msg.role]">
                    <span>[[ msg.text ]]</span>

                </div>
                <!-- 临时 AI 回复 -->
                <div v-if="awaiting_ai_reply" class="message assistant temp">
                    <span>AI正在回复</span>
                    <span class="spinner"></span>
                </div>
            </div>

            <!-- 输入区域 -->
            <el-row type="flex" align="middle" class="input-group" style="margin-top: 10px;">
                <el-col :span="4">
                    <el-button type="success" icon="el-icon-upload" @click="uploadImage" :disabled="loading">上传</el-button>
                    <input type="file" ref="imageInput" accept="image/*" style="display: none;" @change="handleImageUpload">
                </el-col>
                <el-col :span="14">
                    <el-input v-model="message" placeholder="输入消息..." @keyup.enter.native="sendMessage" :disabled="loading"></el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="sendMessage" :disabled="loading">发送</el-button>
                </el-col>
                <el-col :span="2">
                    <el-button type="warning" @click="clearMessages" :disabled="loading">清除</el-button>
                </el-col>
            </el-row>

            <!-- 图片预览 -->
            <div v-if="imagePreview" style="margin-top: 10px;">
                <img :src="imagePreview" alt="图片预览" style="max-width: 100%; max-height: 150px; border-radius: 8px; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);">
            </div>
        </div>
    </div>

    <!-- 引入 Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <!-- 引入 Element UI -->
    <script src="https://unpkg.com/element-ui@2.15.13/lib/index.js"></script>
    <!-- Vue 应用脚本 -->
    <script>
        new Vue({
            el: '#app',
            delimiters: ['[[', ']]'],  // 更改插值符号以避免与 Jinja2 冲突
            data: {
                messages: [],
                message: '',
                img_name: '',
                img_url: '',
                imagePreview: '',
                awaiting_ai_reply: false,
                last_message_id: 0,
                loading: false
            },
            methods: {
                showLoading() {
                    document.getElementById('loading-overlay').style.display = 'flex';
                },
                hideLoading() {
                    document.getElementById('loading-overlay').style.display = 'none';
                },
                disableInputs() {
                    this.loading = true;
                },
                enableInputs() {
                    this.loading = false;
                },
                loadMessages() {
                    fetch('/get_messages')
                        .then(response => response.json())
                        .then(data => {
                            this.messages = data.messages;

                            // 检测是否有新的 AI 回复
                            const aiMessages = this.messages.filter(msg => msg.role === 'assistant');
                            if (aiMessages.length > 0) {
                                const latestAiMessage = aiMessages[aiMessages.length - 1];
                                if (latestAiMessage.id > this.last_message_id) {
                                    // 有新的 AI 回复，取消等待状态
                                    this.awaiting_ai_reply = false;
                                    this.last_message_id = latestAiMessage.id;
                                }
                            }

                            // 如果最后一条消息不是 AI 回复，且正在等待 AI 回复，则保持等待状态
                            if (this.awaiting_ai_reply && this.messages.length > 0) {
                                const lastMsg = this.messages[this.messages.length - 1];
                                if (lastMsg.role !== 'assistant') {
                                    this.awaiting_ai_reply = true;
                                }
                            }

                            // 滚动到底部
                            this.$nextTick(() => {
                                const messagesDiv = document.getElementById('messages');
                                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                            });
                        })
                        .catch(error => {
                            console.error('加载消息时出错:', error);
                            this.$message.error('加载消息时出错');
                        });
                },
                sendMessage() {
                    if (this.message.trim() === '' && this.img_name === '') {
                        this.$message.warning('请输入消息或上传图片');
                        return;
                    }

                    this.showLoading();
                    this.disableInputs();

                    const payload = {
                        'message': this.message,
                        'img_name': this.img_name,
                        'img_url': this.img_url,
                        'max_length': 500
                    };

                    fetch('/send_message', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(payload)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            // 清空输入框和图片信息
                            this.message = '';
                            this.img_name = '';
                            this.img_url = '';
                            this.imagePreview = '';

                            // 设置等待 AI 回复状态
                            this.awaiting_ai_reply = true;
                        } else {
                            this.$alert('发送失败: ' + data.message, '错误', {
                                confirmButtonText: '确定',
                            });
                        }
                        this.hideLoading();
                        this.enableInputs();
                        this.loadMessages();
                    })
                    .catch(error => {
                        console.error('发送消息时出错:', error);
                        this.hideLoading();
                        this.enableInputs();
                        this.$message.error('发送消息时出错');
                    });
                },
                uploadImage() {
                    this.$refs.imageInput.click();
                },
                handleImageUpload(event) {
                    const file = event.target.files[0];
                    if (file) {
                        // 显示预览
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            this.imagePreview = e.target.result;
                        };
                        reader.readAsDataURL(file);

                        // 上传图片到后端
                        this.showLoading();
                        this.disableInputs();

                        const formData = new FormData();
                        formData.append('image', file);

                        fetch('/upload_image', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'success') {
                                this.img_name = data.img_name;
                                this.img_url = data.img_url;
                                this.$message.success('图片上传成功');
                            } else {
                                this.$alert('图片上传失败: ' + data.message, '错误', {
                                    confirmButtonText: '确定',
                                });
                                this.img_name = '';
                                this.img_url = '';
                                this.imagePreview = '';
                            }
                            this.hideLoading();
                            this.enableInputs();
                            // 清除文件输入
                            this.$refs.imageInput.value = '';
                        })
                        .catch(error => {
                            console.error('上传图片时出错:', error);
                            this.hideLoading();
                            this.enableInputs();
                            this.$message.error('上传图片时出错');
                            this.img_name = '';
                            this.img_url = '';
                            this.imagePreview = '';
                        });
                    }
                },
                clearMessages() {
                    this.$confirm('确定要清除所有消息吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.showLoading();
                        this.disableInputs();
                        fetch('/clear_messages', {
                            method: 'POST'
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'success') {
                                this.loadMessages();
                                this.$message.success('已创建新的对话');
                            } else {
                                this.$alert('清除失败: ' + data.message, '错误', {
                                    confirmButtonText: '确定',
                                });
                            }
                            this.hideLoading();
                            this.enableInputs();
                        })
                        .catch(error => {
                            console.error('清除消息时出错:', error);
                            this.hideLoading();
                            this.enableInputs();
                            this.$message.error('清除消息时出错');
                        });
                    }).catch(() => {
                        // 取消操作
                    });
                },
                createNewConversation() {
                    this.showLoading();
                    this.disableInputs();
                    fetch('/create_conversation', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            this.loadMessages();
                            this.$message.success('已创建新的对话');
                        } else {
                            this.$alert('创建对话失败: ' + data.message, '错误', {
                                confirmButtonText: '确定',
                            });
                        }
                        this.hideLoading();
                        this.enableInputs();
                    })
                    .catch(error => {
                        console.error('创建对话时出错:', error);
                        this.hideLoading();
                        this.enableInputs();
                        this.$message.error('创建对话时出错');
                    });
                }
            },
            mounted() {
                // 初始加载消息
                this.loadMessages();
                // 定时刷新消息，每2秒调用一次 loadMessages
                setInterval(this.loadMessages, 2000);
            }
        });
    </script>
</body>
</html>